package com.lp.util.iot;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.core.task.TaskExecutor;

import com.alibaba.fastjson.JSON;
import com.lp.bo.AlarmTriggerRecordBO;
import com.lp.bo.AliyunParamBO;
import com.lp.bo.BussinessTriggerBO;
import com.lp.bo.ContactUserInfoBO;
import com.lp.bo.ContactorBO;
import com.lp.bo.IotAlarmInfoBO;
import com.lp.bo.IotHistoryTriggerInfoBO;
import com.lp.bo.IotNodeInfoBO;
import com.lp.bo.IotSensorInfoBO;
import com.lp.bo.IotTriggerInfoBO;
import com.lp.bo.ProDictionaryInfoBO;
import com.lp.bo.UserAccountInfoBO;
import com.lp.cache.CacheName;
import com.lp.cache.ProCacheUtil;
import com.lp.cache.ProCache.UserAccountThread;
import com.lp.cfg.ProConfig;
import com.lp.cfg.ProConfig.AliyunShortMessage;
import com.lp.common.CodeIot;
import com.lp.common.Constants;
import com.lp.dao.BaseDao;
import com.lp.service.base.MailService;
import com.lp.service.base.ShortMessageService;
import com.lp.util.AliyunSmsAndVoiceUtil;
import com.lp.util.DateUtils;
import com.lp.util.LogUtil;
import com.lp.util.ObjectUtil;
import com.lp.util.SpringApplicationContext;

import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.WxMpTemplateMessage;

public class IotTrigger  {

	/**
	 * 触发器工作
	 * @param obj
	 * @param dao 
	 */
	public static Integer trigger(IotSensorInfoBO obj, BaseDao dao){
		try{
			// 根据 IotSensorInfoBO 获取触发器列表
			String sensorDevicePort = obj.getNode_id()+"-"+ obj.getSensor_device_id()+"-"+obj.getPort_id();
			// 获取触发器缓存
			IotSensorInfoBO iotSensorInfoBo = ProCacheUtil.getCache(CacheName.SENSORTRIGGERINFO, sensorDevicePort, obj);

			int exception_flag = 0 ;
			// trigger 不能为空
			if( iotSensorInfoBo!=null && ObjectUtil.isNotEmpty(iotSensorInfoBo.getTriggerList())  &&  ObjectUtil.isNotEmpty(obj.getSdata()) ){
				List<IotTriggerInfoBO> triggerList = iotSensorInfoBo.getTriggerList();
				for( IotTriggerInfoBO trigger : triggerList ){
					Boolean trigger_flag = false;
					String message ="" ;
					// 搜集报警信息信息
					BussinessTriggerBO bussinessMessgae = new BussinessTriggerBO() ;
					
					// 判断触发器是否为开启状态，如果为关闭状态，继续循环下一个触发器
					// 判断是否超过了触发时间间隔，如果没有超过触发时间间隔，继续循环下一个触发器
					if( trigger.getIot_trigger_status() == CodeIot.IOT_TRIGGER_STATUS.STOP 
							|| (! ObjectUtil.hasNull(trigger.getLast_trigger_time(),trigger.getTrigger_inteval_time()) 
							&& DateUtils.getMinusFromCurrent(trigger.getLast_trigger_time(), trigger.getTrigger_inteval_time())<0 )){
						continue ;
					}
					// 触发器类型值
					Integer triggerType = trigger.getIot_trigger_condition_type() ;
					// 触发条件参数
					String[] conditions = trigger.getCondition_params().split(",");
					
					String measure = getConvertValue(obj.getSdata(),obj.getMeasure_unit_type());
					
					// 判断触发条件类型，如果触发条件中有带时间的触发器类型
					if( triggerType.equals( CodeIot.TRIGGER_CONDITION_TYPE.OVERTOPX_OVERTIME ) 
							||  triggerType.equals( CodeIot.TRIGGER_CONDITION_TYPE.UNDERY_OVERTIME )
							||  triggerType.equals( CodeIot.TRIGGER_CONDITION_TYPE.SENSOR_VALUE_MONITOR )){
						// 如果有缓存，判断是否超过了触发间隔，如果超过触发间隔，触发，否则不处理
						IotTriggerInfoBO cacheTrigger = ProCacheUtil.timeTirggerListCache.get(trigger.getId());
						if( triggerType.equals( CodeIot.TRIGGER_CONDITION_TYPE.OVERTOPX_OVERTIME )  ){
							// 数值超过{M}分钟高于{X}
							if (obj.getSdata() > Double.valueOf(conditions[0]) ) {
								if (decideTrigger(trigger, cacheTrigger, conditions)) {
									trigger_flag = true;
									// 触发动作,并添加触发历史数据
									message =  trigger.getName()+ ",传感器（" + obj.getScene_name()
											+ "/"  +obj.getNode_name()+"/"
											+ iotSensorInfoBo.getName() + "），当前为" + obj.getSdata()+ " "+measure
											+ " ,高于" + conditions[0] +" "+ measure + "，超过"
											+ Integer.valueOf(conditions[1])  + "分钟，请及时处理。";
									// 报警信息
									bussinessMessgae.setSmsType(1);
									bussinessMessgae.setVocieType(1);
									bussinessMessgae.setMessage(message);
									// 短信
									Map<String,String> aliyunSms = new HashMap<>();
									aliyunSms.put("alarm_name", trigger.getName()) ;
									aliyunSms.put("pro_name",  obj.getScene_name()) ;
									aliyunSms.put("device", obj.getNode_name()) ;
									aliyunSms.put("sensor", iotSensorInfoBo.getName()) ;
									aliyunSms.put("time", DateUtils.format(DateUtils.simpleALL, new Date()) ) ;
									aliyunSms.put("value", obj.getSdata()+ " "+measure) ;
									aliyunSms.put("alarm_condition", " 高于" + conditions[0] +" "+ measure + "，超过"
											+ Integer.valueOf(conditions[1])  + "分钟") ;
									bussinessMessgae.setAliyunSms(aliyunSms);
									// 电话
									Map<String,String> aliyunVoice = new HashMap<>();
									aliyunVoice.put("pro_name",  obj.getScene_name()) ;
									aliyunVoice.put("device", obj.getNode_name()) ;
									aliyunVoice.put("sensor", iotSensorInfoBo.getName()) ;
									bussinessMessgae.setAliyunSmsVoice(aliyunVoice);
									
									// 处理缓存
									ProCacheUtil.timeTirggerListCache.remove(trigger.getId());
								}else{
									continue ;
								}
							} else {
								ProCacheUtil.timeTirggerListCache.remove(trigger.getId());
							}
						}
						// 数值超过{M}分钟低于{Y}
						else if(  triggerType.equals( CodeIot.TRIGGER_CONDITION_TYPE.UNDERY_OVERTIME )  ){
							if (obj.getSdata() < Double.valueOf(conditions[0]) ) {
								if (decideTrigger(trigger, cacheTrigger, conditions)) {
									trigger_flag = true;
									// 触发动作,并添加触发历史数据
									message = trigger.getName()+ ",传感器（" + obj.getScene_name() + "/"  +obj.getNode_name()+"/"+
											iotSensorInfoBo.getName() + "），当前为" + obj.getSdata()+" "+ measure
											 + "低于" + conditions[0] +" "+ measure +"，超过"
											+ Integer.valueOf(conditions[1])  + "分钟，请及时处理。";
									// 处理缓存
									ProCacheUtil.timeTirggerListCache.remove(trigger.getId());
									
									// 报警信息
									bussinessMessgae.setSmsType(1);
									bussinessMessgae.setVocieType(1);
									bussinessMessgae.setMessage(message);
									// 短信
									Map<String,String> aliyunSms = new HashMap<>();
									aliyunSms.put("alarm_name", trigger.getName()) ;
									aliyunSms.put("pro_name",  obj.getScene_name()) ;
									aliyunSms.put("device", obj.getNode_name()) ;
									aliyunSms.put("sensor", iotSensorInfoBo.getName()) ;
									aliyunSms.put("time", DateUtils.format(DateUtils.simpleALL, new Date()) ) ;
									aliyunSms.put("value", obj.getSdata()+ " "+measure) ;
									aliyunSms.put("alarm_condition", " 低于" + conditions[0] +" "+ measure + "，超过"
											+ Integer.valueOf(conditions[1])  + "分钟") ;
									bussinessMessgae.setAliyunSms(aliyunSms);
									// 电话
									Map<String,String> aliyunVoice = new HashMap<>();
									aliyunVoice.put("pro_name",  obj.getScene_name()) ;
									aliyunVoice.put("device", obj.getNode_name()) ;
									aliyunVoice.put("sensor", iotSensorInfoBo.getName()) ;
									bussinessMessgae.setAliyunSmsVoice(aliyunVoice);
									
								}else{
									continue ;
								}
							} else {
								ProCacheUtil.timeTirggerListCache.remove(trigger.getId());
							}
						}else if(triggerType.equals( CodeIot.TRIGGER_CONDITION_TYPE.SENSOR_VALUE_MONITOR )){
							// 传感器数值监控,一直不变情况
							IotSensorInfoBO sensorInfo = ProCacheUtil.getCache(CacheName.SENSORINFO_NSP, obj.getNode_id()+"-"+obj.getSensor_device_id()+"-"+obj.getPort_id());
							if (obj.getSdata() == sensorInfo.getSdata()+0 ) {
								if (decideTrigger(trigger, cacheTrigger, conditions)) {
									trigger_flag = true;
									// 触发动作,并添加触发历史数据
									message = trigger.getName()+ ",传感器（" + obj.getScene_name() + "/"  +obj.getNode_name()+"/"+
											iotSensorInfoBo.getName() + "），当前为" + obj.getSdata()+" "+ measure
											 + "数值无变化，超过"
											+ Integer.valueOf(conditions[conditions.length-1])  + "分钟，请及时处理。";
									// 处理缓存
									ProCacheUtil.timeTirggerListCache.remove(trigger.getId());
									
									// 报警信息
									bussinessMessgae.setSmsType(1);
									bussinessMessgae.setVocieType(1);
									bussinessMessgae.setMessage(message);
									// 短信
									Map<String,String> aliyunSms = new HashMap<>();
									aliyunSms.put("alarm_name", trigger.getName()) ;
									aliyunSms.put("pro_name",  obj.getScene_name()) ;
									aliyunSms.put("device", obj.getNode_name()) ;
									aliyunSms.put("sensor", iotSensorInfoBo.getName()) ;
									aliyunSms.put("time", DateUtils.format(DateUtils.simpleALL, new Date()) ) ;
									aliyunSms.put("value", obj.getSdata()+ " "+measure) ;
									aliyunSms.put("alarm_condition", " 数值无变化，，超过"
											+ Integer.valueOf(conditions[conditions.length-1])  + "分钟") ;
									bussinessMessgae.setAliyunSms(aliyunSms);
									// 电话
									Map<String,String> aliyunVoice = new HashMap<>();
									aliyunVoice.put("pro_name",  obj.getScene_name()) ;
									aliyunVoice.put("device", obj.getNode_name()) ;
									aliyunVoice.put("sensor", iotSensorInfoBo.getName()) ;
									bussinessMessgae.setAliyunSmsVoice(aliyunVoice);
									
								}else{
									continue ;
								}
							} else {
								ProCacheUtil.timeTirggerListCache.remove(trigger.getId());
							}
						}else{
							continue ;
						}
						
					}
					// 没有时间积累型的
					else{
						// 数值高于{X}
						if( triggerType.equals( CodeIot.TRIGGER_CONDITION_TYPE.OVERTOPX )  ){
							if (obj.getSdata() > Double.valueOf(conditions[0]) ) {
								trigger_flag = true;
								// 触发动作,并添加触发历史数据
								message = trigger.getName()+ ",传感器（" +obj.getScene_name() + "/"  +obj.getNode_name()+"/"+
										iotSensorInfoBo.getName()  + "），当前为" + obj.getSdata()+" "+measure
										+ " ,高于" + conditions[0] +" "+ measure + "，请及时处理。";
								
								// 报警信息
								bussinessMessgae.setSmsType(1);
								bussinessMessgae.setVocieType(1);
								bussinessMessgae.setMessage(message);
								// 短信
								Map<String,String> aliyunSms = new HashMap<>();
								aliyunSms.put("alarm_name", trigger.getName()) ;
								aliyunSms.put("pro_name",  obj.getScene_name()) ;
								aliyunSms.put("device", obj.getNode_name()) ;
								aliyunSms.put("sensor", iotSensorInfoBo.getName()) ;
								aliyunSms.put("time", DateUtils.format(DateUtils.simpleALL, new Date()) ) ;
								aliyunSms.put("value", obj.getSdata()+ " "+measure) ;
								aliyunSms.put("alarm_condition", " 高于" + conditions[0] +" "+ measure) ;
								bussinessMessgae.setAliyunSms(aliyunSms);
								// 电话
								Map<String,String> aliyunVoice = new HashMap<>();
								aliyunVoice.put("pro_name",  obj.getScene_name()) ;
								aliyunVoice.put("device", obj.getNode_name()) ;
								aliyunVoice.put("sensor", iotSensorInfoBo.getName()) ;
								bussinessMessgae.setAliyunSmsVoice(aliyunVoice);
								
							}
						}
						//  数值低于{Y}
						else if(triggerType.equals( CodeIot.TRIGGER_CONDITION_TYPE.UNDERY ) ){
							if (obj.getSdata() < Double.valueOf(conditions[0]) ) {
								trigger_flag = true;
								// 触发动作,并添加触发历史数据
								message = trigger.getName()+ "传感器（" + obj.getScene_name() + "/"  +obj.getNode_name()+"/"+
										iotSensorInfoBo.getName() + "），当前为" + obj.getSdata()+" "+measure
										+" 低于" + conditions[0] +" "+ measure + "，请及时处理。";
								
								// 报警信息
								bussinessMessgae.setSmsType(1);
								bussinessMessgae.setVocieType(1);
								bussinessMessgae.setMessage(message);
								// 短信
								Map<String,String> aliyunSms = new HashMap<>();
								aliyunSms.put("alarm_name", trigger.getName()) ;
								aliyunSms.put("pro_name",  obj.getScene_name()) ;
								aliyunSms.put("device", obj.getNode_name()) ;
								aliyunSms.put("sensor", iotSensorInfoBo.getName()) ;
								aliyunSms.put("time", DateUtils.format(DateUtils.simpleALL, new Date()) ) ;
								aliyunSms.put("value", obj.getSdata()+ " "+measure) ;
								aliyunSms.put("alarm_condition", " 低于" + conditions[0] +" "+ measure) ;
								bussinessMessgae.setAliyunSms(aliyunSms);
								// 电话
								Map<String,String> aliyunVoice = new HashMap<>();
								aliyunVoice.put("pro_name",  obj.getScene_name()) ;
								aliyunVoice.put("device", obj.getNode_name()) ;
								aliyunVoice.put("sensor", iotSensorInfoBo.getName()) ;
								bussinessMessgae.setAliyunSmsVoice(aliyunVoice);
								
							}
						}
						// 数值在{X}和{Y}之间
						else if(triggerType.equals( CodeIot.TRIGGER_CONDITION_TYPE.XY_OVERMIDDLE )){
							if (obj.getSdata() > Double.valueOf(conditions[0]) &&
									obj.getSdata() < Double.valueOf(conditions[1]) ) {
								trigger_flag = true;
								// 触发动作,并添加触发历史数据
								message =trigger.getName()+ ",传感器（" +  obj.getScene_name() + "/"  +obj.getNode_name()+"/"
										+ iotSensorInfoBo.getName() + "），当前为" + obj.getSdata()+" "+ measure
										+ " ,在" + conditions[0] + "," + conditions[1] +" "+ measure+" 之间，请及时处理。";
								
								// 报警信息
								bussinessMessgae.setSmsType(1);
								bussinessMessgae.setVocieType(1);
								bussinessMessgae.setMessage(message);
								// 短信
								Map<String,String> aliyunSms = new HashMap<>();
								aliyunSms.put("alarm_name", trigger.getName()) ;
								aliyunSms.put("pro_name",  obj.getScene_name()) ;
								aliyunSms.put("device", obj.getNode_name()) ;
								aliyunSms.put("sensor", iotSensorInfoBo.getName()) ;
								aliyunSms.put("time", DateUtils.format(DateUtils.simpleALL, new Date()) ) ;
								aliyunSms.put("value", obj.getSdata()+ " "+measure) ;
								aliyunSms.put("alarm_condition", " 在" + conditions[0] + "," + conditions[1] +" "+ measure) ;
								bussinessMessgae.setAliyunSms(aliyunSms);
								// 电话
								Map<String,String> aliyunVoice = new HashMap<>();
								aliyunVoice.put("pro_name",  obj.getScene_name()) ;
								aliyunVoice.put("device", obj.getNode_name()) ;
								aliyunVoice.put("sensor", iotSensorInfoBo.getName()) ;
								bussinessMessgae.setAliyunSmsVoice(aliyunVoice);
								
							}
						}
						// 数值={X}
						else if(triggerType.equals( CodeIot.TRIGGER_CONDITION_TYPE.EQUAL )){
							if (obj.getSdata() +0f == Float.valueOf(conditions[0])+0 ) {
								trigger_flag = true;
								// 触发动作,并添加触发历史数据
								message = trigger.getName()+ ",传感器（" +  obj.getScene_name() + "/"  +obj.getNode_name()+"/"
										+ iotSensorInfoBo.getName() + "），当前为" + obj.getSdata() + " "+measure
										+ "  等于" + conditions[0]+" "+measure +"，请及时处理。";
								
								// 报警信息
								bussinessMessgae.setSmsType(1);
								bussinessMessgae.setVocieType(1);
								bussinessMessgae.setMessage(message);
								// 短信
								Map<String,String> aliyunSms = new HashMap<>();
								aliyunSms.put("alarm_name", trigger.getName()) ;
								aliyunSms.put("pro_name",  obj.getScene_name()) ;
								aliyunSms.put("device", obj.getNode_name()) ;
								aliyunSms.put("sensor", iotSensorInfoBo.getName()) ;
								aliyunSms.put("time", DateUtils.format(DateUtils.simpleALL, new Date()) ) ;
								aliyunSms.put("value", obj.getSdata()+ " "+measure) ;
								aliyunSms.put("alarm_condition", " 等于" + conditions[0]+" "+measure) ;
								bussinessMessgae.setAliyunSms(aliyunSms);
								// 电话
								Map<String,String> aliyunVoice = new HashMap<>();
								aliyunVoice.put("pro_name",  obj.getScene_name()) ;
								aliyunVoice.put("device", obj.getNode_name()) ;
								aliyunVoice.put("sensor", iotSensorInfoBo.getName()) ;
								bussinessMessgae.setAliyunSmsVoice(aliyunVoice);
								
							}
						}
						else if(triggerType.equals( CodeIot.TRIGGER_CONDITION_TYPE.PEROID_MAX_OVER_PERCENT )){
							List<IotSensorInfoBO> iotSensorInfos = ProCacheUtil.getCache(CacheName.SensorPeroidValue, trigger.getId()+"" );
							if(iotSensorInfos!=null){
								if(iotSensorInfos.size()>= Double.valueOf(conditions[0])+0   ){
									// 可以判断了,取出最大值
									double max_value  = getMaxData(iotSensorInfos) ;
//									LogUtil.errorLog("长度：" + iotSensorInfos.size() +", max_value:" + max_value +",当前传感器数值：" +obj.getSdata()   );
									if( (obj.getSdata()+0) >  max_value *(1+Double.valueOf(conditions[1])/100.0 ) ){
										trigger_flag = true;
										// 触发动作,并添加触发历史数据
										message = trigger.getName()+ ",传感器（" +  obj.getScene_name() + "/"  +obj.getNode_name()+"/"
												+ iotSensorInfoBo.getName() + "），当前为" + obj.getSdata() + " "+measure
												+ " 超过了最近" + conditions[0]+"组数据中最大值的 "+ conditions[1]+"%"  +"，请及时处理。";
										
										// 报警信息
										bussinessMessgae.setSmsType(1);
										bussinessMessgae.setVocieType(1);
										bussinessMessgae.setMessage(message);
										// 短信
										Map<String,String> aliyunSms = new HashMap<>();
										aliyunSms.put("alarm_name", trigger.getName()) ;
										aliyunSms.put("pro_name",  obj.getScene_name()) ;
										aliyunSms.put("device", obj.getNode_name()) ;
										aliyunSms.put("sensor", iotSensorInfoBo.getName()) ;
										aliyunSms.put("time", DateUtils.format(DateUtils.simpleALL, new Date()) ) ;
										aliyunSms.put("value", obj.getSdata()+ " "+measure) ;
										aliyunSms.put("alarm_condition", " 超过了最近" + conditions[0]+"组数据中最大值的 "+ conditions[1]+"%" ) ;
										bussinessMessgae.setAliyunSms(aliyunSms);
										// 电话
										Map<String,String> aliyunVoice = new HashMap<>();
										aliyunVoice.put("pro_name",  obj.getScene_name()) ;
										aliyunVoice.put("device", obj.getNode_name()) ;
										aliyunVoice.put("sensor", iotSensorInfoBo.getName()) ;
										bussinessMessgae.setAliyunSmsVoice(aliyunVoice);
									}
									// 换数据了
									iotSensorInfos.remove(0);
									
								}
								iotSensorInfos.add(obj);
							}else{
								ProCacheUtil.addCache(CacheName.SensorPeroidValue, trigger.getId()+"", new ArrayList<IotSensorInfoBO>() ); 
							}
						}
						else if(triggerType.equals( CodeIot.TRIGGER_CONDITION_TYPE.PEROID_MIN_OVER_PERCENT )){
							List<IotSensorInfoBO> iotSensorInfos = ProCacheUtil.getCache(CacheName.SensorPeroidValue, trigger.getId()+"" );
							if(iotSensorInfos!=null){
								if(iotSensorInfos.size()>= Double.valueOf(conditions[0])+0   ){
									// 可以判断了,取出最大值
									double minvalue  = getMinData(iotSensorInfos) ;
									if( (obj.getSdata()+0) <  minvalue *( Double.valueOf(conditions[1])/100.0 ) ){
										trigger_flag = true;
										// 触发动作,并添加触发历史数据
										message = trigger.getName()+ ",传感器（" +  obj.getScene_name() + "/"  +obj.getNode_name()+"/"
												+ iotSensorInfoBo.getName() + "），当前为" + obj.getSdata() + " "+measure
												+ " 低于了最近" + conditions[0]+"组数据中最小值的 "+ conditions[1]+"%"  +"，请及时处理。";
										
										// 报警信息
										bussinessMessgae.setSmsType(1);
										bussinessMessgae.setVocieType(1);
										bussinessMessgae.setMessage(message);
										// 短信
										Map<String,String> aliyunSms = new HashMap<>();
										aliyunSms.put("alarm_name", trigger.getName()) ;
										aliyunSms.put("pro_name",  obj.getScene_name()) ;
										aliyunSms.put("device", obj.getNode_name()) ;
										aliyunSms.put("sensor", iotSensorInfoBo.getName()) ;
										aliyunSms.put("time", DateUtils.format(DateUtils.simpleALL, new Date()) ) ;
										aliyunSms.put("value", obj.getSdata()+ " "+measure) ;
										aliyunSms.put("alarm_condition", " 低于了最近" + conditions[0]+"组数据中最小值的 "+ conditions[1]+"%") ;
										bussinessMessgae.setAliyunSms(aliyunSms);
										// 电话
										Map<String,String> aliyunVoice = new HashMap<>();
										aliyunVoice.put("pro_name",  obj.getScene_name()) ;
										aliyunVoice.put("device", obj.getNode_name()) ;
										aliyunVoice.put("sensor", iotSensorInfoBo.getName()) ;
										bussinessMessgae.setAliyunSmsVoice(aliyunVoice);
									}
									// 换数据了
									iotSensorInfos.remove(0);
									
								}
								iotSensorInfos.add(obj);
							}else{
								ProCacheUtil.addCache(CacheName.SensorPeroidValue, trigger.getId()+"", new ArrayList<IotSensorInfoBO>() ); 
							}
						}
						else if(triggerType.equals( CodeIot.TRIGGER_CONDITION_TYPE.EXCEPTION_DATA_SOLVE )){
							if (obj.getSdata() < Double.valueOf(conditions[0]) ||
									obj.getSdata() > Double.valueOf(conditions[1]) ) {
								trigger_flag = true;
								exception_flag = 1 ;
								// 数据异常，需要过滤
								message =trigger.getName()+ ",传感器（" +  obj.getScene_name() + "/"  +obj.getNode_name()+"/"
										+ iotSensorInfoBo.getName() + "），当前为" + obj.getSdata()+" "+ measure
										+ " ,在" + conditions[0] + "," + conditions[1] +" "+ measure+"区间之外，请及时处理。";
								
								// 报警信息
								bussinessMessgae.setSmsType(1);
								bussinessMessgae.setVocieType(1);
								bussinessMessgae.setMessage(message);
								// 短信
								Map<String,String> aliyunSms = new HashMap<>();
								aliyunSms.put("alarm_name", trigger.getName()) ;
								aliyunSms.put("pro_name",  obj.getScene_name()) ;
								aliyunSms.put("device", obj.getNode_name()) ;
								aliyunSms.put("sensor", iotSensorInfoBo.getName()) ;
								aliyunSms.put("time", DateUtils.format(DateUtils.simpleALL, new Date()) ) ;
								aliyunSms.put("value", obj.getSdata()+ " "+measure) ;
								aliyunSms.put("alarm_condition", " 在" + conditions[0] + "," + conditions[1] +" "+ measure+"区间之外") ;
								bussinessMessgae.setAliyunSms(aliyunSms);
								// 电话
								Map<String,String> aliyunVoice = new HashMap<>();
								aliyunVoice.put("pro_name",  obj.getScene_name()) ;
								aliyunVoice.put("device", obj.getNode_name()) ;
								aliyunVoice.put("sensor", iotSensorInfoBo.getName()) ;
								bussinessMessgae.setAliyunSmsVoice(aliyunVoice);
							}
						}else{
							continue ;
						}
					}
					
					if (trigger_flag) {
						// 这边对于一次触发的处理
						if( trigger.getTrigger_inteval_time()!= null 
								&& trigger.getTrigger_inteval_time()+0 < 1  ){
							// 单次触发
							if( trigger.getIs_worked()!= null && trigger.getIs_worked() ){
								continue ;
							}
						}
						
						// 已经触发，更新触发器的缓存
						trigger.setIs_worked(true);
						
						trigger.setLast_trigger_time(new Date());
						// 触发
						triggerWork(obj, trigger, bussinessMessgae ,dao , 1);
						// 判断是否需要报警
						if (trigger.getIot_trigger_alarm_flag() != null
								&& CodeIot.ALARM_FLAG.OPEN == trigger
										.getIot_trigger_alarm_flag()) {
							// 添加报警
							alarmWrok(obj, trigger, message,dao , 1);
						}
					}else{
						// 这边处理，报警恢复
						if(trigger.getIs_worked() != null && trigger.getIs_worked() &&
								trigger.getRecovery() == 36 		// 报警恢复工作
								){
							// 恢复正常，发送恢复正常的信息
							// 主要的就是发消息
							// 控制设备就不需要了
							IotNodeInfoBO nodeInfo = ProCacheUtil.getCache(CacheName.NODEINFO, obj.getNode_id().toString());
							message = trigger.getName()  +"恢复正常，设备（" + obj.getScene_name() + "/"  +nodeInfo.getName()+"/"+
									iotSensorInfoBo.getName()+ "）已恢复到正常范围，当前数值为  "+ obj.getSdata()+" "+ measure
									 + "，请及时关注。";
							
							// 报警信息
							bussinessMessgae.setSmsType(3);
							bussinessMessgae.setVocieType(3);
							bussinessMessgae.setMessage(message);
							// 短信
							Map<String,String> aliyunSms = new HashMap<>();
							aliyunSms.put("alarm_name", trigger.getName()) ;
							aliyunSms.put("pro_name",  obj.getScene_name()) ;
							aliyunSms.put("device", obj.getNode_name()) ;
							aliyunSms.put("sensor", iotSensorInfoBo.getName()) ;
							aliyunSms.put("time", DateUtils.format(DateUtils.simpleALL, new Date()) ) ;
							aliyunSms.put("value", obj.getSdata()+ " "+measure) ;
							bussinessMessgae.setAliyunSms(aliyunSms);
							// 电话
							Map<String,String> aliyunVoice = new HashMap<>();
							aliyunVoice.put("pro_name",  obj.getScene_name()) ;
							aliyunVoice.put("device", obj.getNode_name()) ;
							aliyunVoice.put("sensor", iotSensorInfoBo.getName()) ;
							bussinessMessgae.setAliyunSmsVoice(aliyunVoice);
							
							IotTrigger.triggerWork(obj, trigger, bussinessMessgae , dao , 2);
							
							if (trigger.getIot_trigger_alarm_flag() != null
									&& CodeIot.ALARM_FLAG.OPEN == trigger
											.getIot_trigger_alarm_flag()) {
								// 添加报警
								IotTrigger.alarmWrok(obj, trigger, message, dao , 2);
							}
						}
						
						trigger.setIs_worked(false);
					}
					// 数据过滤退出
					if(exception_flag ==1 ){
						return -1 ;
					}
				}
			}
		}catch(Exception e){
			LogUtil.errorLog(e);
			return -1 ;
		}
		return 0;
	}
	
	/**
	 * 添加报警信息
	 * @param obj
	 * @param trigger
	 * @param message
	 * @param dao
	 */
	public static void alarmWrok(IotSensorInfoBO obj, IotTriggerInfoBO trigger, String message, BaseDao dao , Integer type) {
		try {
			String[] conditions = trigger.getCondition_params().split(",");
			IotAlarmInfoBO alarm = new IotAlarmInfoBO();
			alarm.setSensor_id(trigger.getFrom_sensor_id());
			alarm.setIot_trigger_alarm_level(trigger.getIot_trigger_alarm_level());
			alarm.setDescription(message);
			if(type == 1){
				alarm.setName(trigger.getName()+"报警");
			}else if( type == 2){
				alarm.setName(trigger.getName()+"恢复");
			}
			alarm.setAlarm_sdata(Float.parseFloat(conditions[0]));
			alarm.setSdata(obj.getSdata());
			
			ContactorBO contactor = JSON.parseObject(trigger.getAction_params(), ContactorBO.class);
			if( ObjectUtil.isNotEmpty(contactor.getContactor()) ){
				String[] contact_user_ids = contactor.getContactor().split(",") ;
				String name = "" ;
				for(int i=0 ; i< contact_user_ids.length ; i++ ){
					ContactUserInfoBO contactUserInfo = new ContactUserInfoBO();
					contactUserInfo.setId(Integer.parseInt(contact_user_ids[i]) );
					contactUserInfo = dao.selectOne("ContactUserInfo.selectOne", contactUserInfo);
					if(ObjectUtil.isNotEmpty(contactUserInfo)){
						name += "," +contactUserInfo.getName() ;					
					}
				}
				alarm.setContact_names( name.length()>0?name.substring(1):name   );
			}
			
			
			alarm.setIot_alarm_process_status(CodeIot.PROCESS_STATUS.NO);
			dao.insert("IotAlarmInfo.insert", alarm);
		} catch (Exception e) {
			LogUtil.errorLog(e);
		}
	}

	public static String getConvertValue(double sdata,Integer code_measure){
		try{
			com.lp.bean.ProDictionaryInfo obj = ProCacheUtil.getCache(CacheName.DICTIONARY, code_measure.toString(),
												new com.lp.bean.ProDictionaryInfo());
			if(ObjectUtil.isNotEmpty(obj.getValue())){
				String[] value = obj.getValue().split(",");
				if( Double.parseDouble(value[0].split(":")[0]) == sdata ){
					return value[0].split(":")[1];
				}else if(Double.parseDouble(value[1].split(":")[0]) == sdata){
					return value[1].split(":")[1];
				}				
			}else{
				return obj.getName();
			}
		}catch(Exception e){
			LogUtil.errorLog(e);
		}
		return "" ;
	}
	
	private static Boolean  decideTrigger(IotTriggerInfoBO trigger, IotTriggerInfoBO cacheTrigger, String[] conditions) {
		if (ObjectUtil.isNotEmpty(cacheTrigger) ) {
			if (DateUtils.getMinusFromCurrent(cacheTrigger.getAtime(),
					Integer.valueOf(conditions[conditions.length - 1])*60 ) >= 0) {
				return true;
			}
		} else {
			trigger.setAtime(new Date());
			ProCacheUtil.timeTirggerListCache.put(trigger.getId(), trigger);
		}
		return false;
	}
	
	
	/**
	 * 事务处理
	 * 
	 * @param param
	 * @param trigger
	 * @return
	 */
	public static void triggerWork(IotSensorInfoBO param , IotTriggerInfoBO trigger, BussinessTriggerBO message,BaseDao dao , Integer type) {
		try {
			// 触发详情
			StringBuffer triggerInfo = new StringBuffer() ;
			
			String[] triggerActionType = trigger.getIot_trigger_action_type().split(",");
			for (int i = 0; i < triggerActionType.length; i++) {
				if ((CodeIot.ACTION_TYPE.CONTROL_DEVICE + "").equals(triggerActionType[i])) {
					triggerInfo.append( sendDevice(param, trigger, message ,dao, type ) )	;
				} else if ((CodeIot.ACTION_TYPE.MESSAGE_WECHAT + "").equals(triggerActionType[i])) {
					triggerInfo.append( sendWechat(param, trigger, message ,dao, type ) );
				} else if ((CodeIot.ACTION_TYPE.MESSAGE_SMS + "").equals(triggerActionType[i])) {
					triggerInfo.append( sendSms(param, trigger, message ,dao) );
				} else if ((CodeIot.ACTION_TYPE.MESSAGE_MAIL + "").equals(triggerActionType[i])) {
					triggerInfo.append( sendEmal(param, trigger, message ,dao , type ) );
				} else if ((CodeIot.ACTION_TYPE.MESSAGE_VOICE + "").equals(triggerActionType[i])) {
					triggerInfo.append( sendSmsVoice(param, trigger, message ,dao  ) );
				}
			}
			
			if (trigger.getIot_trigger_alarm_flag() != null
					&& CodeIot.ALARM_FLAG.OPEN == trigger
							.getIot_trigger_alarm_flag()) {
				if(type == 1){
					triggerInfo.append("产生系统报警消息;");					
				}else if(type == 2){
					triggerInfo.append("产生设备报警恢复消息;");		
				}
			}
			
			String[] conditions = trigger.getCondition_params().split(",");
			
			// 插入历史记录中
			IotHistoryTriggerInfoBO history = new IotHistoryTriggerInfoBO();
			history.setSdata(param.getSdata());
			
			history.setDescription(triggerInfo.toString());
			
			history.setName(trigger.getName());
			// 插入触发数值
			history.setTrigger_value(conditions[0]);
			history.setFrom_sensor_id(trigger.getFrom_sensor_id());
			history.setTo_sensor_id(trigger.getTo_sensor_id());
			history.setIot_trigger_condition_type(trigger.getIot_trigger_condition_type());
			history.setIot_trigger_action_type(trigger.getIot_trigger_action_type());
			history.setAction_params(trigger.getAction_params());
			history.setCondition_params(trigger.getCondition_params());
			history.setIot_trigger_alarm_level(trigger.getIot_trigger_alarm_level());
			history.setIot_trigger_alarm_flag(trigger.getIot_trigger_alarm_flag());
			history.setTrigger_inteval_time(trigger.getTrigger_inteval_time());
			dao.insert("IotHistoryTriggerInfo.insert", history);
		} catch (Exception e) {
			LogUtil.errorLog(e);
		}
	}
	
	public static String sendDevice(IotSensorInfoBO param, IotTriggerInfoBO trigger, BussinessTriggerBO message,BaseDao dao ,Integer flag ) {
		
		if( ObjectUtil.isEmpty(trigger.getAction_params()) ){
			return "" ;
		}
		
		// 将string 转json
		ContactorBO contactor = JSON.parseObject(trigger.getAction_params(), ContactorBO.class);
		
		String info = "" ;
		
		// 控制传感器的信息
		IotSensorInfoBO controlSensor = ProCacheUtil.getCache(CacheName.SENSORINFO, contactor.getControl_device() );
		
		info = "控制"+controlSensor.getName() +"设备为";
		ProDictionaryInfoBO bo =  ProCacheUtil.getCache(CacheName.DICTIONARY, controlSensor.getMeasure_unit_type().toString()) ;
//		String[] controlValue =  bo.getValue().split(",") ; 
	
		// 转发 控制传感器 to_sensor_id , action_param
		IotSensorInfoBO sensor = new IotSensorInfoBO(controlSensor.getId());
		if( flag == 1 ){
			// 正常触发
			if(  contactor.getControl_device_status().equals(CodeIot.ALARM_FLAG.OPEN.toString()) ){
				info += "打开";
				sensor.setRequest_sdata(1f);	
			}else{
				info += "关闭";
				sensor.setRequest_sdata(0f);
			}
		}else if(flag == 2){
			// 恢复触发
			if( ! contactor.getControl_device_status().equals(CodeIot.ALARM_FLAG.OPEN.toString()) ){
				info += "打开";
				sensor.setRequest_sdata(1f);	
			}else{
				info += "关闭";
				sensor.setRequest_sdata(0f);
			}
		}
		
		dao.update("IotSensorInfo.update", sensor);
		
		// 发送消息给LPM,控制设备
		ProtocolUtil.sendControlSensorCommand(sensor);
		return info+"状态；" ;
	}
	
	/**
	 * 拨打电话给某人
	 * @param param
	 * @param trigger
	 * @param message
	 * @param dao
	 * @return
	 */
	public static String sendSmsVoice(IotSensorInfoBO param, IotTriggerInfoBO trigger, final BussinessTriggerBO message,final BaseDao dao){
		// 根据action_param 获取联系人id，然后拨打给某人
		if( ObjectUtil.isEmpty(trigger.getAction_params()) ){
			return "" ;
		}
		
		final Integer add_user_id = trigger.getAid() ;
		if( ObjectUtil.isEmpty(add_user_id) ){
			return "语音报警触发器没有归属用户；" ;
		}
		final UserAccountInfoBO userAccount = ProCacheUtil.getCache(CacheName.USERACCOUNT_ID, add_user_id.toString()) ;
		if( ObjectUtil.isNotEmpty(userAccount) && userAccount.getVoice_num() >0 ){
			// 可以发短信
			userAccount.setVoice_num( userAccount.getVoice_num() -1 );
			// 减少用户 短信数量，插入发短信信息
			TaskExecutor taskExecutor = (TaskExecutor) SpringApplicationContext.getBean("taskExecutor");
			taskExecutor.execute(new Runnable() {
				@Override
				public void run() {
					// 减少用户短信数量
					UserAccountInfoBO userAccountBo = new UserAccountInfoBO();
					userAccountBo.setId(userAccount.getId());
					dao.update("UserAccountInfo.updatevoicenum", userAccountBo) ;
					
					// 增加用户触发
					AlarmTriggerRecordBO alarmTriggerRecord = new AlarmTriggerRecordBO() ;
					alarmTriggerRecord.setUser_id(add_user_id);
					alarmTriggerRecord.setTrigger_type(CodeIot.ACTION_TYPE.MESSAGE_VOICE);
					alarmTriggerRecord.setContent(message.getMessage());
					alarmTriggerRecord.setAtime(new Date());
					dao.insert("AlarmTriggerRecord.insert", alarmTriggerRecord) ;
				}
			});
		}else{
			return "语音报警触发，用户没有余额；" ;
		}
		
		// 将string 转json
		ContactorBO contactor = JSON.parseObject(trigger.getAction_params(), ContactorBO.class);
		String[] contact_user_ids = contactor.getContactor().split(",") ;
		String name = "" ;
		for(int i=0 ; i< contact_user_ids.length ; i++ ){
			ContactUserInfoBO contactUserInfo = new ContactUserInfoBO();
			contactUserInfo.setId(Integer.parseInt(contact_user_ids[i]) );
			contactUserInfo = dao.selectOne("ContactUserInfo.selectOne", contactUserInfo);
			if (ObjectUtil.isNotEmpty(contactUserInfo) && ObjectUtil.isNotEmpty(contactUserInfo.getPhone())) {
				name+= ","+contactUserInfo.getName() ;
				
				AliyunParamBO aliyunParamBo = new AliyunParamBO() ;
				aliyunParamBo.setPhonenumber(contactUserInfo.getPhone());
				if( message.getSmsType() == 1 ){
					aliyunParamBo.setTemplateCode(ProConfig.AliyunShortMessage.VOICE_TEMPLATE1);
				}else if( message.getSmsType() == 2 ){
					aliyunParamBo.setTemplateCode(ProConfig.AliyunShortMessage.VOICE_TEMPLATE2);
				}else if( message.getSmsType() == 3 ){
					aliyunParamBo.setTemplateCode(ProConfig.AliyunShortMessage.VOICE_TEMPLATE3);
				}else if( message.getSmsType() == 4 ){
					aliyunParamBo.setTemplateCode(ProConfig.AliyunShortMessage.VOICE_TEMPLATE4);
				}
				aliyunParamBo.setCalledShowNumber( ProConfig.AliyunShortMessage.CALLEDSHOWNUMBER );
				aliyunParamBo.setTemplateParam( JSON.toJSONString(message.getAliyunSmsVoice()) );
				AliyunSmsAndVoiceUtil.sendSmsVoice(aliyunParamBo);
			}
		}
		if("".equals(name)){
			return "" ;
		}
		return "拨打电话给"+ name.substring(1) +"；" ;
	}
	
	public static String sendSms(IotSensorInfoBO param, IotTriggerInfoBO trigger, final BussinessTriggerBO message,final BaseDao dao) {
		// 根据action_param 获取联系人id，然后发送端短信给某人
		
		if( ObjectUtil.isEmpty(trigger.getAction_params()) ){
			return "" ;
		}
		// 将string 转json
		ContactorBO contactor = JSON.parseObject(trigger.getAction_params(), ContactorBO.class);
		String[] contact_user_ids = contactor.getContactor().split(",") ;
		String name = "" ; 
		// ---
		final Integer add_user_id = trigger.getAid() ;
		if( ObjectUtil.isEmpty(add_user_id) ){
			return "短信报警触发器没有归属用户；" ;
		}
		final UserAccountInfoBO userAccount = ProCacheUtil.getCache(CacheName.USERACCOUNT_ID, add_user_id.toString()) ;
		if( ObjectUtil.isNotEmpty(userAccount) && userAccount.getSms_num() >0 ){
			// 可以发短信
			userAccount.setSms_num( userAccount.getSms_num()-1 );
			// 减少用户 短信数量，插入发短信信息
			TaskExecutor taskExecutor = (TaskExecutor) SpringApplicationContext.getBean("taskExecutor");
			taskExecutor.execute(new Runnable() {
				@Override
				public void run() {
					// 减少用户短信数量
					UserAccountInfoBO userAccountBo = new UserAccountInfoBO();
					userAccountBo.setId(userAccount.getId());
					dao.update("UserAccountInfo.updatesmsnum", userAccountBo) ;
					
					// 增加用户触发
					AlarmTriggerRecordBO alarmTriggerRecord = new AlarmTriggerRecordBO() ;
					alarmTriggerRecord.setUser_id(add_user_id);
					alarmTriggerRecord.setTrigger_type(CodeIot.ACTION_TYPE.MESSAGE_SMS);
					alarmTriggerRecord.setContent(message.getMessage());
					alarmTriggerRecord.setAtime(new Date());
					dao.insert("AlarmTriggerRecord.insert", alarmTriggerRecord) ;
				}
			});
		}else{
			return "短信报警触发，用户没有余额；" ;
		}
				
		for(int i=0 ; i< contact_user_ids.length ; i++ ){
			ContactUserInfoBO contactUserInfo = new ContactUserInfoBO();
			contactUserInfo.setId(Integer.parseInt(contact_user_ids[i]) );
			contactUserInfo = dao.selectOne("ContactUserInfo.selectOne", contactUserInfo);
			if (ObjectUtil.isNotEmpty(contactUserInfo) && ObjectUtil.isNotEmpty(contactUserInfo.getPhone())) {
				name+= ","+contactUserInfo.getName() ;
				// 这边通过spring 获取短信的实体
				
				AliyunParamBO aliyunParamBo = new AliyunParamBO() ;
				aliyunParamBo.setPhonenumber(contactUserInfo.getPhone());
				if( message.getSmsType() == 1 ){
					aliyunParamBo.setTemplateCode(ProConfig.AliyunShortMessage.SMS_TEMPCODE1);
				}else if( message.getSmsType() == 2 ){
					aliyunParamBo.setTemplateCode(ProConfig.AliyunShortMessage.SMS_TEMPCODE2);
				}else if( message.getSmsType() == 3 ){
					aliyunParamBo.setTemplateCode(ProConfig.AliyunShortMessage.SMS_TEMPCODE3);
				}else if( message.getSmsType() == 4 ){
					aliyunParamBo.setTemplateCode(ProConfig.AliyunShortMessage.SMS_TEMPCODE4);
				}
				aliyunParamBo.setSignaName( ProConfig.AliyunShortMessage.SIGNATURE );
				aliyunParamBo.setTemplateParam( JSON.toJSONString(message.getAliyunSms()) );
				AliyunSmsAndVoiceUtil.sendSms(aliyunParamBo);
				
				// 云片网
//				ShortMessageService shortMessageService = (ShortMessageService) SpringApplicationContext.getBean("shortMessageServiceImpl");
//				shortMessageService.sendSms(message.getMessage() , contactUserInfo.getPhone());					
			}
		}
		if("".equals(name)){
			return "" ;
		}
		return "发送短信给"+ name.substring(1) +"；" ;
	}
	
	/**
	 * 发送微信通知
	 * 
	 * @param param
	 * @param trigger
	 * @return
	 */
	public static String sendWechat(IotSensorInfoBO param, IotTriggerInfoBO trigger, BussinessTriggerBO message,BaseDao dao,Integer flag) {
		if( ObjectUtil.isEmpty(trigger.getAction_params()) ){
			return "" ;
		}
		// 将string 转json
		ContactorBO contactor = JSON.parseObject(trigger.getAction_params(), ContactorBO.class);
		String[] contact_user_ids = contactor.getContactor().split(",") ;
		
		String name = "" ;
		for(int i=0 ; i< contact_user_ids.length ; i++ ){
			ContactUserInfoBO contactUserInfo = new ContactUserInfoBO();
			try{
				contactUserInfo.setId(Integer.parseInt(contact_user_ids[i]) );				
			}catch(Exception e){
				continue ;
			}
			contactUserInfo = dao.selectOne("ContactUserInfo.selectOne", contactUserInfo);
			if (ObjectUtil.isNotEmpty(contactUserInfo) && ObjectUtil.isNotEmpty(contactUserInfo.getWx_key() )) {
				name += "," +contactUserInfo.getName() ;
				// 给当前联系人发送微信通知
				// 传感器缓存
				IotSensorInfoBO sensorInfo = ProCacheUtil.getCache(CacheName.SENSORINFO_NSP, param.getNode_id()+"-"+
												param.getSensor_device_id()+"-"+param.getPort_id());
				// 报警信息
				param.getNode_name() ;
				// 当前传感器数值  
				param.getSdata() ;
				// 场景名称
				param.getId();
				param.getScene_name() ; String measure = getConvertValue(param.getSdata(),param.getMeasure_unit_type()); ; // 单位
				// 时间
				new Date();sensorInfo.getName();
				
				WxMpService wxMpserver = (WxMpService) SpringApplicationContext.getBean("wxMpService");
				
				WxMpTemplateMessage wxTemplate = new WxMpTemplateMessage();
				wxTemplate.setUrl(ProConfig.LOCAL_DOMAIN+"/service/wiot/alarm" );
				
				if(flag == 1){
					wxTemplate.setDatas(Arrays.asList( new WxMpTemplateData(Constants.WeiXinTemplate.FIRST, "您有一条新的报警消息，请及时处理！"),
							new WxMpTemplateData(Constants.WeiXinTemplate.KEYWORD1, param.getScene_name()+"/"+param.getNode_name() +"/"+sensorInfo.getName(),"#03a9f4" ),
							new WxMpTemplateData(Constants.WeiXinTemplate.KEYWORD2,  "微信消息" ),
							new WxMpTemplateData(Constants.WeiXinTemplate.KEYWORD3,  DateUtils.format(DateUtils.simpleALL, new Date()) ),
							new WxMpTemplateData(Constants.WeiXinTemplate.KEYWORD4,  message.getMessage() ,"#e62112" ),
							new WxMpTemplateData(Constants.WeiXinTemplate.REMARK,  "点击查看详情" )));
				}else if(flag == 2){
					wxTemplate.setDatas(Arrays.asList( new WxMpTemplateData(Constants.WeiXinTemplate.FIRST, "您有一条新的设备报警恢复消息，请及时关注！"),
							new WxMpTemplateData(Constants.WeiXinTemplate.KEYWORD1, param.getScene_name()+"/"+param.getNode_name() +"/"+sensorInfo.getName(),"#03a9f4" ),
							new WxMpTemplateData(Constants.WeiXinTemplate.KEYWORD2,  "微信消息" ),
							new WxMpTemplateData(Constants.WeiXinTemplate.KEYWORD3,  DateUtils.format(DateUtils.simpleALL, new Date()) ),
							new WxMpTemplateData(Constants.WeiXinTemplate.KEYWORD4,  message.getMessage() ,"#e62112" ),
							new WxMpTemplateData(Constants.WeiXinTemplate.REMARK,  "点击查看详情" )));
				}
				
				wxTemplate.setToUser(contactUserInfo.getWx_key() );
				wxTemplate.setTemplateId(ProConfig.WEIXIN.NOTICE_1);
				try {
					wxMpserver.templateSend(wxTemplate);
				} catch (Exception e) {
					e.printStackTrace();
				}	
			}
		}
		if("".equals(name)){
			return "" ;
		}
		return "发送微信消息给" + name.substring(1) +"；" ;
	}
	
	/**
	 * 发送邮件通知
	 * 
	 * @param param
	 * @param trigger
	 * @return
	 */
	public static String sendEmal(IotSensorInfoBO param, IotTriggerInfoBO trigger, BussinessTriggerBO message,BaseDao dao,Integer flag) {

		if( ObjectUtil.isEmpty(trigger.getAction_params()) ){
			return "" ;
		}
		// 将string 转json
		ContactorBO contactor = JSON.parseObject(trigger.getAction_params(), ContactorBO.class);
		String[] contact_user_ids = contactor.getContactor().split(",") ;
		String name = "" ;
		for(int i=0 ; i < contact_user_ids.length ; i++ ){
			ContactUserInfoBO contactUserInfo = new ContactUserInfoBO();
			contactUserInfo.setId(Integer.parseInt(contact_user_ids[i]) );
			contactUserInfo = dao.selectOne("ContactUserInfo.selectOne", contactUserInfo);
			if (ObjectUtil.isNotEmpty(contactUserInfo) && ObjectUtil.isNotEmpty(contactUserInfo.getEmail())) {
				// 发邮件
				name += ","+contactUserInfo.getName() ;
				Map<String, Object> mail = new HashMap<String, Object>();
				mail.put("name", contactUserInfo.getName());
				mail.put("email", contactUserInfo.getEmail());
				mail.put("message", message.getMessage() );
				MailService mailService = (MailService) SpringApplicationContext.getBean("mailServiceImpl");
				if(flag == 1){
					mailService.send(contactUserInfo.getEmail(),  trigger.getName() + "触发提醒邮件",
							"tpl/vm/iot_trigger_notice.vm", mail);			
				}else if(flag == 2){
					mailService.send(contactUserInfo.getEmail(),  trigger.getName() + "设备报警恢复提醒邮件",
							"tpl/vm/iot_trigger_notice.vm", mail);			
				}
			}
		}
		if("".equals(name)){
			return "" ;
		}
		return "发送邮件给"+name.substring(1)+"；" ;
	}
	
	
	private static double getMaxData(List<IotSensorInfoBO> iotSensorInfos){
		double maxvalue = 0 ;
		for(IotSensorInfoBO e:iotSensorInfos ){
			if(e.getSdata()+0 > maxvalue ){
				maxvalue = e.getSdata() ;
			}
		}
		return maxvalue ;
	}
	
	private static double getMinData(List<IotSensorInfoBO> iotSensorInfos){
		double minvalue = iotSensorInfos.get(0).getSdata()+0f ;
		for(IotSensorInfoBO e:iotSensorInfos ){
			if(e.getSdata()+0 < minvalue ){
				minvalue = e.getSdata() ;
			}
		}
		return minvalue ;
	}
	
}
